<template>
  <div class="max-w-4xl mx-auto p-4">
    <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm">
      <h2 class="text-2xl font-bold mb-6 text-gray-900 dark:text-white">XML美化工具</h2>
      
      <!-- 输入区域 -->
      <div class="mb-6">
        <textarea
          v-model="inputXml"
          placeholder="请输入要格式化的XML..."
          rows="8"
          class="w-full px-4 py-3 rounded-lg bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none font-mono"
        ></textarea>
      </div>

      <!-- 操作按钮 -->
      <div class="flex flex-wrap gap-4 mb-6">
        <button
          @click="beautifyXml"
          class="px-4 py-2 rounded-lg bg-blue-500 hover:bg-blue-600 text-white font-medium transition-colors"
        >
          格式化
        </button>
        <button
          @click="minifyXml"
          class="px-4 py-2 rounded-lg bg-gray-500 hover:bg-gray-600 text-white font-medium transition-colors"
        >
          压缩
        </button>
      </div>

      <!-- 结果区域 -->
      <div v-if="outputXml" class="space-y-4">
        <div class="flex justify-between items-center">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">处理结果：</h3>
          <button
            @click="copyToClipboard"
            class="px-3 py-1 rounded-lg bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
            :title="copied ? '已复制！' : '复制到剪贴板'"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
            </svg>
            <span>{{ copied ? '已复制' : '复制' }}</span>
          </button>
        </div>
        <pre class="w-full p-4 rounded-lg bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 overflow-x-auto font-mono text-sm">{{ outputXml }}</pre>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="mt-4 p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg">
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const inputXml = ref('');
const outputXml = ref('');
const error = ref('');
const copied = ref(false);

// XML格式化函数
const beautifyXml = () => {
  try {
    error.value = '';
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(inputXml.value, 'text/xml');
    
    // 检查解析错误
    const parserError = xmlDoc.querySelector('parsererror');
    if (parserError) {
      throw new Error('XML解析错误：请检查XML语法是否正确');
    }

    // 格式化XML
    const serializer = new XMLSerializer();
    let xmlString = serializer.serializeToString(xmlDoc);
    
    // 添加缩进和换行
    xmlString = formatXml(xmlString);
    
    outputXml.value = xmlString;
  } catch (err) {
    error.value = err instanceof Error ? err.message : '处理XML时发生错误';
  }
};

// XML压缩函数
const minifyXml = () => {
  try {
    error.value = '';
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(inputXml.value, 'text/xml');
    
    // 检查解析错误
    const parserError = xmlDoc.querySelector('parsererror');
    if (parserError) {
      throw new Error('XML解析错误：请检查XML语法是否正确');
    }

    // 序列化XML（移除空白）
    const serializer = new XMLSerializer();
    const xmlString = serializer.serializeToString(xmlDoc)
      .replace(/>\s+</g, '><') // 移除标签间的空白
      .replace(/\s+$/g, ''); // 移除末尾空白
    
    outputXml.value = xmlString;
  } catch (err) {
    error.value = err instanceof Error ? err.message : '处理XML时发生错误';
  }
};

// 格式化XML字符串
const formatXml = (xml: string): string => {
  let formatted = '';
  let indent = '';
  const tab = '  '; // 使用两个空格作为缩进
  
  xml.split(/>\s*</).forEach(node => {
    if (node.match(/^\/\w/)) {
      // 结束标签，减少缩进
      indent = indent.substring(tab.length);
    }
    
    formatted += indent + '<' + node + '>\r\n';
    
    if (node.match(/^<?\w[^>]*[^/]$/)) {
      // 开始标签，增加缩进
      indent += tab;
    }
  });
  
  // 处理自闭合标签和注释
  return formatted
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\r\n\s*\r\n/g, '\r\n') // 移除多余的空行
    .replace(/\n\s*\n/g, '\n');
};

// 复制到剪贴板
const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(outputXml.value);
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  } catch (err) {
    error.value = '复制失败，请手动复制';
  }
};
</script> 